import 'dart:io';

import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/ute/uteped_device.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'device_search_state.dart';

class DeviceSearchLogic extends BaseController {

  static const methodScanDevice = "scanDevice";
  static const methodCancelScan = "cancelScan";
  static const methodCheckGPS = "checkGPS";
  static const methodIsGPSOpen = "isGPSOpen";
  static const remotePath = "device";

  final DeviceSearchState state = DeviceSearchState();
  final UTEPedDevice utePedDevice = UTEPedDevice.instance;

  void _checkGps() {
    bRemoteReqAsync(methodIsGPSOpen, {}).then((value) => {
          if (!value)
            {
              Get.defaultDialog(
                  title: LocaleKeys.info.ts,
                  middleText: LocaleKeys.gps_message.ts,
                  barrierDismissible: false,
                  onCancel: () => {},
                  onConfirm: () =>
                      {Get.back(), vRemoteReqAsync(methodCheckGPS, {})})
            }
          else
            {scanDevice()}
        });
  }

  @override
  Future<void> onReady() async {
    var granted = await Permission.location.isGranted;
    if (!granted) {
      var value = await Permission.location.request();
      if(!value.isGranted){
        showPermissionDialog(LocaleKeys.location_permission_tips.ts);
      }
    }

    if (Platform.isAndroid) {
      granted = await Permission.locationWhenInUse.isGranted;
      if (!granted) {
        granted = await Permission.locationWhenInUse.request().isGranted;
        if(!granted){
          showPermissionDialog(LocaleKeys.location_permission_tips.ts);
        }
      }
    }

    granted = await Permission.bluetooth.isGranted;
    if (!granted) {
      var value = await Permission.bluetooth.request();
      if(!value.isGranted && Platform.isIOS){
        showPermissionDialog(LocaleKeys.bluetooth_permission_tips.ts);
      }
    }
    super.onReady();
  }

  @override
  void onResumed() {
    super.onResumed();
    checkBluetooth();
  }

  @override
  void initState() {
    checkBluetooth();
  }

  @override
  void onClose() {
    cancelScan();
    super.onClose();
  }

  @override
  String getRemotePath() {
    return remotePath;
  }

  @override
  void onRemoteEvent(event, method) {
    if (method == methodScanDevice) {
      state.isScanning.value = false;
      List list = event['list'];
      if (list.isNotEmpty) {
        state.deviceList = event['list'];
        Get.offNamed("device/bind", arguments: state.deviceList);
      }
      else {
        scanDevice();
      }
    }
  }

  void checkBluetooth() {
    utePedDevice.isBluetoothEnable().then(
        (value) => {
          state.isBluetoothEnable = value,
          update(), _checkGps()
        }
    );
  }

  Future<void> scanDevice() async {
    if (!state.isBluetoothEnable) {
      return;
    }
    state.isScanning.value = true;
    await vRemoteReqAsync(methodScanDevice, {"type": "list"});
  }

  Future<void> cancelScan() async {
    vRemoteReqAsync(methodCancelScan, {});
  }

  void retry() {
    checkBluetooth();
    scanDevice();
  }

}
